﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

namespace USERS.CYT369.COM.Controllers
{
    public class AccountController : AllowAnonymousController
    {
        public UserManager<USERS.CYT369.COM.MODELS.SysUser> UserManager { get; set; }
        public SignInManager<USERS.CYT369.COM.MODELS.SysUser> SignInManager { get; set; }

        public AccountController(UserManager<USERS.CYT369.COM.MODELS.SysUser> userManager, SignInManager<USERS.CYT369.COM.MODELS.SysUser> signInManager) {
            this.UserManager = userManager;
            this.SignInManager = signInManager;
        }

        #region 重定向
        private ActionResult LocalRedirect(string returnUrl, string resultUrl, string tgt)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.LoginDefaultRedirect;
            }

            var argsSign = "?";
            if (returnUrl.IndexOf("?") > 0)
            {
                argsSign = "&";
            }
            returnUrl = $"{returnUrl}{argsSign}ticket={tgt}&resultUrl={resultUrl}";

            return Redirect(returnUrl);
        }

        private string MakeRedirectUrl(string returnUrl, string resultUrl, string tgt)
        {
            if (!string.IsNullOrEmpty(returnUrl))
            {
                var argsSign = "?";
                if (returnUrl.IndexOf("?") > 0)
                {
                    argsSign = "&";
                }
                returnUrl = $"{returnUrl}{argsSign}ticket={tgt}&resultUrl={resultUrl}";
            }

            return returnUrl;
        }
        #endregion

        #region 用户登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Login(string returnUrl, string resultUrl, string appId, bool? force)
        {
            if (force == true)
            {
                await this.SignInManager.SignOutAsync();
            }
            else if (this.User.Identity.IsAuthenticated)
            {
                var tgt = this.UserSession.TGT;
                if (!string.IsNullOrEmpty(tgt))
                {
                    return LocalRedirect(returnUrl, resultUrl, tgt);
                }
                else
                {
                    await this.SignInManager.SignOutAsync();
                }
            }

            var cookie = Request.Cookies[USERS.CYT369.COM.UTILITY.ConstStringClass.RememberUser];
            if (cookie != null)
            { // 记住用户名和密码，自动登录
                var kv = USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.DesKV;
                var iv = USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.DesIV;
                string loginInfo = USERS.CYT369.COM.UTILITY.Encrypt.DesDecrypt(cookie, kv, iv);
                if (!string.IsNullOrEmpty(loginInfo))
                {
                    var sps = loginInfo.Split(new string[] { "!--" }, StringSplitOptions.RemoveEmptyEntries);
                    if (sps != null && sps.Length == 3)
                    {
                        var userName = sps[0];
                        var password = sps[1];
                        var expiredTime = DateTime.Now;
                        if (DateTime.TryParse(sps[2], out expiredTime))
                        {
                            if (expiredTime > DateTime.Now)
                            {
                                // cookie有效，直接登录
                                var retVal = new USERS.CYT369.COM.Models.ExecuteResult();
                                var user =await DoSignIn(userName, password, false, true, appId, retVal);
                                AfterLogin(user, true, appId, returnUrl, resultUrl, retVal);
                                if (retVal.Result && !string.IsNullOrEmpty(retVal.Msg))
                                {
                                    return Redirect(retVal.Msg);
                                }
                            }
                        }
                    }
                }
            }

            ViewBag.ReturnUrl = returnUrl;
            ViewBag.ResultUrl = resultUrl;
            ViewBag.AppID = appId;
            return View("Login2");
        }


        /// <summary>
        /// 用户登录(Web)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Login([FromBody]USERS.CYT369.COM.Models.AccountView.LoginViewModel model)
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult();
            if (model != null)
            {
                var captchaCode = CYT369.COM.DAL.RedisService.Instance.GetImageCaptcha(this.HttpContext.Session.Id);
                if (!string.IsNullOrEmpty(captchaCode))
                {

                    if (string.Compare(captchaCode.ToUpper(), model.CaptchaCode.ToUpper(), true) == 0)
                    {
                        #region returnUrl
                        string returnUrl = model.ReturnUrl;
                        if (string.IsNullOrEmpty(returnUrl))
                        {
                            returnUrl = Request.Query["returnUrl"];
                        }
                        if (string.IsNullOrEmpty(returnUrl))
                        {
                            returnUrl = Url.Content(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.LoginDefaultRedirect);
                        }
                        #endregion

                        // 这不会计入到为执行帐户锁定而统计的登录失败次数中
                        // 若要在多次输入错误密码的情况下触发帐户锁定，请更改为 shouldLockout: true
                        var user = await DoSignIn(model.UserName, model.Password, model.RememberMe, true, model.AppID, retVal);
                        AfterLogin(user, model.RememberMe, model.AppID, returnUrl, model.ResultUrl, retVal);
                    }
                    else
                    {
                        retVal.Result = false;
                        retVal.Msg = "错误的验证码";
                    }
                }
                else
                {
                    retVal.Result = false;
                    retVal.Msg = "验证码已过期";
                }
            }
            else
            {
                retVal.Result = false;
                retVal.Msg = "无效的登录尝试";
            }

            return DefaultJson(retVal);
        }

        /// <summary>
        /// 移动登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> MobileLogin([FromBody] USERS.CYT369.COM.Models.AccountView.LoginViewModel model)
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult();
            if (model != null)
            {
                var captchaCode = CYT369.COM.DAL.RedisService.Instance.GetMobileCaptcha(model.UserName);
                if (!string.IsNullOrEmpty(captchaCode))
                {
                    if (string.Compare(captchaCode.ToUpper(), model.CaptchaCode.ToUpper(), true) == 0)
                    {
                        var loginUser = await DoSignIn(model.UserName, model.Password, model.RememberMe, true, model.AppID, retVal);
                        if (loginUser != null)
                        {
                            #region 生成jwt
                            var now = DateTime.UtcNow;
                            var expiredTime = now.AddDays(365);

                            //下面使用 Microsoft.IdentityModel.Tokens帮助库下的类来创建JwtToken
                            //创建安全秘钥
                            var buffer = System.Text.Encoding.ASCII.GetBytes(CYT369.COM.UTILITY.SystemSettingService.Instance.Audience_Secret);
                            var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(buffer);

                            var jwt = new JwtSecurityToken(
                                issuer: CYT369.COM.UTILITY.SystemSettingService.Instance.Audience_Iss,//jwt签发人
                                audience: CYT369.COM.UTILITY.SystemSettingService.Instance.Audience_Aud,//jwt受众
                                claims: new Claim[]
                                {
                                        new System.Security.Claims.Claim(JwtRegisteredClaimNames.NameId, loginUser.Id.ToString()),//声明user id
                                        new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sub, loginUser.UserName),//声明主题
                                        new System.Security.Claims.Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),//JWT ID 唯一标识符
                                        new System.Security.Claims.Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)//发布时间戳 issued timestamp
                                },//jwt一组声明
                                notBefore: now,
                                expires: expiredTime,//jwt令牌过期时间
                                signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)//签名凭证: 安全密钥、签名算法
                            );

                            //生成jwt令牌(json web token)
                            retVal.Result = true;
                            retVal.Data = new
                            {
                                UserInfo = new
                                {
                                    UniqueCode = loginUser.UniqueCode,
                                    UserName = loginUser.UserName,
                                    NickName = loginUser.NickName,
                                    Gender = loginUser.Gender,
                                    Avatar = loginUser.Avatar,
                                    HeaderUrl = loginUser.HeaderUrl,
                                },
                                access_token = new JwtSecurityTokenHandler().WriteToken(jwt),
                                expires_in = (expiredTime - now).TotalSeconds
                            };
                            retVal.Msg = "登录成功";
                            #endregion
                        }
                    }
                    else
                    {
                        retVal.Result = false;
                        retVal.Msg = "错误的验证码";
                    }
                }
                else
                {
                    retVal.Result = false;
                    retVal.Msg = "验证码已过期";
                }
            }
            else
            {
                retVal.Result = false;
                retVal.Msg = "无效的登录尝试";
            }

            return DefaultJson(retVal);
        }

        /// <summary>
        /// 注册手机号 - 获取验证码
        /// </summary>
        /// <param name="m"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetLoginCaptcha(string m, long t)
        {
            string mobileNumber = m;
            var retVal = new Models.ExecuteResult();
            if (!string.IsNullOrEmpty(mobileNumber))
            {
                string errMsg = null;
                if (base.GetMobileCaptcha(mobileNumber, ref errMsg))
                {
                    retVal.Result = true;
                    retVal.Msg = "Success";
                }
                else
                {
                    retVal.Result = false;
                    retVal.Msg = errMsg;
                }
            }
            else
            {
                retVal.Result = false;
                retVal.Msg = "手机号不能为空";
            }

            return DefaultJson(retVal);
        }

        /// <summary>
        /// Web登录时使用
        /// </summary>
        /// <param name="user"></param>
        /// <param name="rememberMe"></param>
        /// <param name="appId"></param>
        /// <param name="returnUrl"></param>
        /// <param name="resultUrl"></param>
        /// <param name="retVal"></param>
        private void AfterLogin(CYT369.COM.MODELS.SysUser user, bool rememberMe, string appId, string returnUrl, string resultUrl, USERS.CYT369.COM.Models.ExecuteResult retVal)
        {
            if (user != null)
            {
                var ticket = USERS.CYT369.COM.Models.LoginHelper.MakeTGT(user);
                this.UserSession.TGT = ticket;
                USERS.CYT369.COM.Models.Ticket.TicketService.Instane.AddTicket(ticket, appId, user, DateTime.Now.AddHours(24));
                this.UserSession.SysUser = user;

                retVal.Result = true;
                retVal.Code = 200;
                retVal.Data = ticket;
                retVal.Msg = MakeRedirectUrl(returnUrl, resultUrl, ticket);
                if (rememberMe)//记住我，设置cookie
                {
//                    string loginInfo = $"{userName}!--{password}!--{DateTime.Now.AddDays(14).ToString("yyyy-MM-dd HH:mm:ss")}";
//                    var kv = USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.DesKV;
//                    var iv = USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.DesIV;

//                    Response.Cookies.Append(USERS.CYT369.COM.UTILITY.ConstStringClass.RememberUser, USERS.CYT369.COM.UTILITY.Encrypt.DesEncrypt(loginInfo, kv, iv), new Microsoft.AspNetCore.Http.CookieOptions()
//                    {
//                        HttpOnly = true,
//#if !DEBUG
//                        Domain = "user.cyt369.com",
//#endif
//                        Expires = DateTime.Now.AddDays(14)
//                    });
                }
            }
        }

        //public async Task<ActionResult> Login([FromBody] USERS.CYT369.COM.Models.AccountView.LoginViewModel model)
        //{

        //}

        /// <summary>
        /// 查找用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> FindUserByName([FromBody] USERS.CYT369.COM.Models.AccountView.LoginViewModel model)
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult();
            if (model != null)
            {
                var appKey = this.Request.Headers["APPKey"];
                var appId = this.Request.Headers["APPID"];

                var user = await this.UserManager.FindByNameAsync(model.UserName);
                retVal.Data = user;
                retVal.Result = true;
                retVal.Msg = "成功";
            }
            else
            {
                retVal.Result = false;
                retVal.Msg = "无效的用户";
            }

            return DefaultJson(retVal);
        }

        private async Task<CYT369.COM.MODELS.SysUser> DoSignIn(string userName, string password, bool rememberMe, bool shouldLockout, string appId, USERS.CYT369.COM.Models.ExecuteResult retVal)
        {
            var result = await this.SignInManager.PasswordSignInAsync(userName, password, rememberMe, shouldLockout);
            if (result.Succeeded)
            {
                var user = await this.UserManager.FindByNameAsync(userName);
                if (user != null)
                {
                    user.PasswordHash = string.Empty;
                    var ip = GetClientUserIp(this.HttpContext);
                    var browserInfo = USERS.CYT369.COM.UTILITY.UserAgentService.Parse(Request.Headers["User-Agent"].ToString());
                    var browser = browserInfo?.BrowserInfo?.Name;
                    var version = browserInfo?.BrowserInfo?.Version;
                    var platform = browserInfo.Platform;
                    var isMobileDevice = platform != null ? platform.IsMobile : false;
                    var mobileDeviceModel = isMobileDevice ? platform?.Model : null;
                    var mobileDeviceManufacturer = isMobileDevice ? platform?.Manufacturer : null;

                    // 记录登录日志
                    new System.Threading.Tasks.Task(delegate ()
                    {
                        try
                        {
                            var app = USERS.CYT369.COM.DAL.SystemService.Instance.GetApp(appId);
                            USERS.CYT369.COM.DAL.UserService.Instance.SaveUserLoginLog(new USERS.CYT369.COM.MODELS.UserLoginLog()
                            {
                                UserID = user.Id,
                                AppID = (app != null ? app.Id : 0),
                                IPAddress = ip,
                                Place = USERS.CYT369.COM.Models.LoginHelper.IpLookup_ipchaxun(ip),
                                Platform = platform?.OperatingSystem,
                                Browser = browser,
                                Version = version,
                                IsMobileDevice = isMobileDevice,
                                MobileDeviceModel = mobileDeviceModel,
                                MobileDeviceManufacturer = mobileDeviceManufacturer,
                                LoginTime = DateTime.Now
                            });
                        }
                        catch (Exception e) { }
                    }).Start();

                    retVal.Result = true;
                    return user;
                }
            }
            else if(result.IsLockedOut)
            {
                retVal.Result = false;
                retVal.Msg = "账户已被锁定";
            }else
            {
                retVal.Result = false;
                retVal.Msg = "登录失败";
            }

            return null;
        }

        /// <summary>
        /// QQ回调
        /// </summary>
        /// <returns></returns>
        public ActionResult qq_callback()
        {
            return View();
        }

        #endregion

        #region 用户注册
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<IActionResult> Register(string returnUrl, string resultUrl, string appId, bool? force)
        {
            if (force == true)
            {
                await this.SignInManager.SignOutAsync();
            }
            else if (this.User.Identity.IsAuthenticated)
            {
                var tgt = this.UserSession.TGT;
                if (!string.IsNullOrEmpty(tgt))
                {
                    return LocalRedirect(returnUrl, resultUrl, tgt);
                }
                else
                {
                    await this.SignInManager.SignOutAsync();
                }
            }

            ViewBag.ReturnUrl = returnUrl;
            ViewBag.ResultUrl = resultUrl;
            ViewBag.AppID = appId;

            return View("Register2");
        }

        /// <summary>
        /// 注册手机号 - 获取验证码
        /// </summary>
        /// <param name="m"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetRegisterCaptcha(string m, long t)
        {
            string mobileNumber = m;
            var retVal = new Models.ExecuteResult();
            if (!string.IsNullOrEmpty(mobileNumber))
            {
                var user = USERS.CYT369.COM.DAL.UserService.Instance.GetUserByPhoneNumber(mobileNumber);
                if (user == null)
                {
                    string errMsg = null;
                    if (base.GetMobileCaptcha(mobileNumber, ref errMsg))
                    {
                        retVal.Result = true;
                        retVal.Msg = "Success";
                    }
                    else
                    {
                        retVal.Result = false;
                        retVal.Msg = errMsg;
                    }
                }
                else
                {
                    retVal.Result = false;
                    retVal.Msg = "该手机号已被其他用户使用";
                }
            }
            else
            {
                retVal.Result = false;
                retVal.Msg = "手机号不能为空";
            }

            return DefaultJson(retVal);
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> Register(USERS.CYT369.COM.Models.AccountView.RegisterViewModel model)
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult();
            if (model != null)
            {
                var captchaCode = CYT369.COM.DAL.RedisService.Instance.GetMobileCaptcha(model.UserName);
                if (!string.IsNullOrEmpty(captchaCode))
                {
                    if (string.Compare(captchaCode.ToUpper(), model.CaptchaCode.ToUpper(), true) == 0)
                    {
                        #region returnUrl
                        string returnUrl = model.ReturnUrl;
                        if (string.IsNullOrEmpty(returnUrl))
                        {
                            returnUrl = Request.Query["returnUrl"];
                        }
                        if (string.IsNullOrEmpty(returnUrl))
                        {
                            returnUrl = Url.Content(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.LoginDefaultRedirect);
                        }
                        #endregion

                        #region SysUser
                        var user = new USERS.CYT369.COM.MODELS.SysUser
                        {
                            UserType = model.UserType,
                            UniqueCode = Guid.NewGuid().ToString(),
                            SecurityStamp = Guid.NewGuid().ToString(),

                            UserName = model.UserName,
                            FullName = model.UserName,
                            NormalizedUserName = model.UserName == null ? "" : model.UserName.ToUpper(),

                            Email = model.Email,
                            NormalizedEmail = model.Email == null ? "" : model.Email.ToUpper(),

                            PhoneNumber = model.PhoneNumber,
                            PhoneNumberConfirmed = true,

                            ChangedTime = DateTime.Now,
                            CreatedTime = DateTime.Now
                        };
                        #endregion

                        var result = await UserManager.CreateAsync(user, model.Password);
                        if (result.Succeeded)
                        {
                            var loginUser = await DoSignIn(user.UserName, model.Password, false, true, model.AppID, retVal);
                            AfterLogin(loginUser, false, model.AppID, returnUrl, model.ResultUrl, retVal);

                        }
                        else if (result.Errors.Count() > 0)
                        {
                            retVal.Result = false;
                            retVal.Msg = result.Errors.ToString();
                        }
                        else
                        {
                            retVal.Result = false;
                            retVal.Msg = "注册用户失败";
                        }
                    }
                    else
                    {
                        retVal.Result = false;
                        retVal.Msg = "错误的验证码";
                    }
                }
                else
                {
                    retVal.Result = false;
                    retVal.Msg = "验证码已过期";
                }
            }
            else
            {
                retVal.Result = false;
                retVal.Msg = "无效的请求";
            }

            return DefaultJson(retVal);
        }
        #endregion

        #region TicketService

        //public ActionResult __TestTicket(string appId, string appKey, string ticket)
        //{
        //    object user = null;
        //    if (USERS.CYT369.COM.DAL.SystemService.Instance.IsEnableApp(appId, appKey))
        //    {
        //        var userTicker = USERS.CYT369.COM.Models.Ticket.TicketService.Instane.GetTicket(ticket);
        //        if (userTicker != null)
        //        {
        //            if (userTicker.ExpiredTime > DateTime.Now)
        //            {
        //                user = userTicker.SysUser; //new Users.CYT369.Com.DAL.Entities.WcfUser(userTicker.SysUser);
        //            }
        //        }
        //    }

        //    return DefaultJson(user);
        //}

        [HttpPost]
        public IActionResult CheckTicket(string appId, string appKey, string ticket)
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult() { Result = false };

            var sso = Request.Headers["SSO"].ToString();
            if (string.Compare(sso, appId, true) == 0)
            {
                if (USERS.CYT369.COM.DAL.SystemService.Instance.IsEnableApp(appId, appKey))
                {
                    var userTicker = USERS.CYT369.COM.Models.Ticket.TicketService.Instane.GetTicket(ticket);
                    if (userTicker != null)
                    {
                        if (userTicker.ExpiredTime > DateTime.Now)
                        {
                            retVal.Data = new USERS.CYT369.COM.MODELS.WcfUser(userTicker.SysUser);
                            retVal.Result = true;
                        }
                        else
                        {
                            retVal.Msg = "超时";
                        }
                    }
                    else
                    {
                        retVal.Msg = "非法key";
                    }
                }
                else
                {
                    retVal.Msg = "未启用";
                }
            }
            else
            {
                retVal.Msg = "Bad Request";
            }

            return DefaultJson(retVal);
        }

        [HttpPost]
        public IActionResult FindUserById(string appId, string appKey, string userId)
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult() { Result = false };

            var sso = Request.Headers["SSO"].ToString();
            if (string.Compare(sso, appId, true) == 0)
            {
                if (USERS.CYT369.COM.DAL.SystemService.Instance.IsEnableApp(appId, appKey))
                {
                    var user = this.UserManager.FindByIdAsync(userId).Result;
                    if (user != null)
                    {
                        retVal.Data = new USERS.CYT369.COM.MODELS.WcfUser(user);
                        retVal.Result = true;
                    }
                    else
                    {
                        retVal.Msg = "NotFound";
                    }
                }
                else
                {
                    retVal.Msg = "未启用";
                }
            }
            else
            {
                retVal.Msg = "Bad Request";
            }

            return DefaultJson(retVal);
        }
        #endregion

        #region 忘记密码
        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(USERS.CYT369.COM.Models.AccountView.ForgotPasswordViewModel model)
        {
            bool success = false;

            if (model != null)
            {
                string errMsg = null;
                if (!base.GetMobileCaptcha(model.PhoneNumber, ref errMsg))
                {
                    ViewBag.ErrorMsg = errMsg;
                }
            }

            if (success)
            {
                return Redirect($"~/Account/ResetPassword?code={DateTime.Now.Ticks}");
            }
            else
            {
                return View(model);
            }
        }
        #endregion

        #region 重置密码
        public ActionResult ResetPassword(string code)
        {
            ViewBag.PhoneNumber = this.UserSession.PhoneNumber;

            return code == null ? View("Error") : View();
        }

        [HttpPost]
        public ActionResult ResetPasswordGetCaptcha(long t)
        {
            var retVal = new USERS.CYT369.COM.Models.ExecuteResult();
            string mobileNumber = this.UserSession.PhoneNumber;

            string errMsg = null;
            if (base.GetMobileCaptcha(mobileNumber, ref errMsg))
            {
                retVal.Msg = $"验证码已发送至您的绑定手机{mobileNumber}，请注意查收！";
            }
            else
            {
                retVal.Msg = errMsg;
            }

            return DefaultJson(retVal);
        }

        [HttpPost]
        public async Task<ActionResult> ResetPassword(USERS.CYT369.COM.Models.AccountView.ResetPasswordViewModel model)
        {
            var captchaCode = CYT369.COM.DAL.RedisService.Instance.GetMobileCaptcha(this.UserSession.PhoneNumber);
            if (!string.IsNullOrEmpty(captchaCode))
            {

                if (string.Compare(captchaCode.ToUpper(), model.CaptchaCode.ToUpper(), true) == 0)
                {
                    string phoneNumber = this.UserSession.PhoneNumber;
                    var user = USERS.CYT369.COM.DAL.UserService.Instance.GetUserByPhoneNumber(phoneNumber);
                    if (user != null)
                    {
                        var token = await this.UserManager.GeneratePasswordResetTokenAsync(user);
                        var result = await this.UserManager.ResetPasswordAsync(user, token, model.Password);
                        if (result.Succeeded)
                        {
                            return Redirect("~/Account/ResetPasswordSuccess");
                        }
                        else
                        {
                            ViewBag.ErrorMsg = "修改密码失败";
                        }
                    }
                    else
                    {
                        ViewBag.ErrorMsg = "修改密码失败";
                    }
                }
                else
                {
                    ViewBag.ErrorMsg = "错误的验证码";
                }
            }
            else
            {
                ViewBag.ErrorMsg = "验证码已过期";
            }

            return View(model);
        }

        public ActionResult ResetPasswordSuccess()
        {
            return View();
        }
        #endregion


        /// <summary>
        /// 退出登录状态
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> LogOff()
        {
            try
            {
                this.UserSession.Clear();
            }
            catch { }

            try
            {
                this.Response.Cookies.Delete(USERS.CYT369.COM.UTILITY.ConstStringClass.RememberUser);
            }
            catch { }

            try
            {
                await this.SignInManager.SignOutAsync();
            }
            catch { }

            //var apps = USERS.CYT369.COM.DAL.SystemService.Instance.GetAllApps();
            return View();
        }
    }
}
